package com.oldking.controller;

import com.oldking.domain.VideoData;
import com.oldking.domain.VideoInfo;
import com.oldking.domain.VideoTask;
import com.oldking.utils.AlertMessageUtil;
import com.oldking.utils.CommonFileUtil;
import com.oldking.utils.CommonTimeUtil;
import com.oldking.utils.UUIDUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import start.StarterClass;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Observable;
import java.util.ResourceBundle;

/**
 * @author itwang
 */
@RestController
public class MainController implements Initializable {

    @FXML
    private TableView tview;
    @FXML
    private TableColumn fileName;
    @FXML
    private TableColumn size;
    @FXML
    private TableColumn frame;
    @FXML
    private TableColumn duration;
    @FXML
    private TableColumn path;
    @FXML
    private TableColumn format;
    @FXML
    private TableColumn opration;

    private StarterClass application;
    @FXML
    private TextField findVideosInput;

    public void setApp(StarterClass application) {
        this.application = application;
    }

    @FXML
    private void OUT_M(ActionEvent event) {
        VideoData.setCurrentTime(0);
        VideoData.setKey("");
        VideoData.setVideoInfoList( FXCollections.observableArrayList());
        tview.setItems(null);
        application.useroutmain();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        List<VideoInfo> videoInfoList = VideoData.getVideoInfoList();
        if (videoInfoList.size() == 0) {
            return;
        }
        initTableColumn();
        ObservableList<VideoInfo> videoInfos = FXCollections.observableArrayList();
        videoInfos.addAll(videoInfoList);
        tview.setItems(videoInfos);
    }

    public void findVideoSubmit() {
        File videoFile = CommonFileUtil.openvidFile();
        ObservableList<VideoInfo> list = getVideoListByFile(videoFile);
        if (list.size() == 0) {
            return;
        }
        initTableColumn();
        ObservableList<VideoInfo> items = tview.getItems();
        items.addAll(list);
        tview.setItems(items);
    }


    private ObservableList<VideoInfo> getVideoListByFile(File videoFile) {
        ObservableList<VideoInfo> list = FXCollections.observableArrayList();
        if (videoFile == null){
            return list;
        }
        // 输入框右值就进行下一步操作
        if (!StringUtils.hasText(videoFile.getPath())) {
            AlertMessageUtil.msg(Alert.AlertType.ERROR, "视频列表", "添加视频失败", "");
            return list;
        }
        // 创建一个读取流对象和文件相关联。
        String videoFileName = videoFile.getName();
        // TODO 判断视频是否已经在列表中存在
        boolean b = hasFileAlready(videoFile.getPath());
        if (b) {
            AlertMessageUtil.msg(Alert.AlertType.ERROR, "视频列表", "该视频文件已经存在", "");
            return list;
        }

        VideoInfo fs = new VideoInfo();
        fs.setId(UUIDUtil.getUUID());
        fs.setFileName(videoFileName);
        fs.setFormat(videoFileName.substring(videoFileName.lastIndexOf(".") + 1, videoFileName.length()));
        String videoSize = CommonFileUtil.formetFileSize(videoFile.length());
        fs.setSize(videoSize);
        setProp(fs, videoFile);
        VideoData.getVideoInfoList().add(fs);
        list.add(fs);
        return list;
    }

    private boolean hasFileAlready(String videoFileName) {
        ObservableList<VideoInfo> items = tview.getItems();
        for (VideoInfo videoInfo : items) {
            if (videoInfo.getPath().equals(videoFileName)) {
                return true;
            }
        }
        return false;
    }

    private void setProp(VideoInfo fs, File videoFile) {
        try {
            fs.setPath(videoFile.getCanonicalPath());
            FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(videoFile);
            fFmpegFrameGrabber.start();

            File file = new File(videoFile.getCanonicalPath());
            if (!CommonFileUtil.imgLocation(file)) {
                AlertMessageUtil.msg(Alert.AlertType.ERROR, "不支持的视频格式，支持格式列表如下:", "mp4|flv|avi|rm|rmvb|wmv|mpeg|3gp|asf|divx|mpg|mpe|mkv|vob", "");
                return;
            }
            //获取帧值
            int frameRateInt = new Double(fFmpegFrameGrabber.getFrameRate()).intValue();
            fs.setFrameRate(frameRateInt);
            fs.setImageHeight(fFmpegFrameGrabber.getImageHeight());
            fs.setImageWidth(fFmpegFrameGrabber.getImageWidth());
            fs.setFrame(String.valueOf(fFmpegFrameGrabber.getLengthInFrames()));
            //获取视频时长
            long duration = fFmpegFrameGrabber.getLengthInTime() / (1000 * 1000);
            String durationTime = CommonTimeUtil.secondToTime(duration);
            fs.setDuration(durationTime);
            fs.setOpration("编辑");
            fFmpegFrameGrabber.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initTableColumn() {
        fileName.setCellValueFactory(new PropertyValueFactory("fileName"));
        size.setCellValueFactory(new PropertyValueFactory("size"));
        frame.setCellValueFactory(new PropertyValueFactory("frame"));
        duration.setCellValueFactory(new PropertyValueFactory("duration"));
        path.setCellValueFactory(new PropertyValueFactory("path"));
        format.setCellValueFactory(new PropertyValueFactory("format"));
        opration.setCellValueFactory(new PropertyValueFactory("opration"));

        opration.setCellFactory(new Callback<TableColumn<VideoInfo, String>, TableCell<VideoInfo, String>>() {
            @Override
            public TableCell<VideoInfo, String> call(TableColumn<VideoInfo, String> param) {
                TableCell<VideoInfo, String> cell = new TableCell<VideoInfo, String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        Button button = new Button("编辑");
                        if (!empty) {
                            this.setGraphic(button);
                        }
                        button.setOnMouseClicked(ActionEvent -> {
                            VideoInfo videoInfo = (VideoInfo)this.getTableRow().getItem();
                            VideoData.setKey(videoInfo.getPath());
                            application.gotoeditvideo(item);
                        });
                    }
                };
                return cell;
            }
        });
    }
}
